
var express = require('express');
var router = express.Router();
var fetch = require('node-fetch');
var session = require('express-session');
var crypto = require('crypto');

const db = require("../../database/models");
const Admin_user = db.admin_user;
const Op = db.Sequelize.Op;

router.post('/login', async function(req, res, next) {
  //console.log(req.body);
  if(!req.body.username||!req.body.password||!req.body){
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }
  let crypto_password = crypto.createHash('md5').update(req.body.password).digest('hex');
  await Admin_user.findAll({
    where:{
      username:req.body.username,
      password:crypto_password
    }
  }).then(data=>{
    //console.log(data.length);
    if(data.length===1){
      req.session.state = true;
      res.send({
        command:'pass to first page',
        message:'登陆成功',
        code:1
      });
    }else{
      res.send({
        command:'redirect to login',
        message:'登陆失败,账号或密码不正确',
        code:0
      });      
    }
  })
  .catch(err => {
    res.status(500).send({
      message:
        err.message || "Some error occurred while check the account."
    });
  });
});

router.post('/regist',function(req, res, next) {
        // Validate request
  if (!req.body||req.body.length===0) {
    res.status(400).send({
      message: "Content can not be empty!"
    });
    return;
  }
  if(req.body.password!==req.body.password2){
    res.send({
      code:0,
      message: "The passwords entered twice are inconsistent!"
    });
    return;
  }

  Admin_user.findAll({
    where:{
      username:req.body.username
    }
  }).then(data=>data.length)
  .then(e=>{
    if(e===1){
      res.send({
        command:'redirect to login',
        message:'用户名已存在',
        code:222,

      });
      
    }else{
        // Create a Admin_user
  delete req.body.password2;
  //md5摘要password
  var admin_user = req.body;
  let crypto_password = crypto.createHash('md5').update(req.body.password).digest('hex');
  req.body.password = crypto_password;

  // Save Admin_user in the database
  Admin_user.create(admin_user)
    .then(data => {
      req.session.state = true;
      res.send({
        data:data,
        message:'创建成功',
        code:1,
        command:'redirect to login'
      });
    })
    .catch(err => {
      res.status(500).send({
        message:
          err.message || "Some error occurred while creating the Admin_user."
      });
    });
    }
  })
  .catch(err => {
    res.status(500).send({
      message:
        err.message || "Some error occurred while check the account."
    });
  });


});

router.get('/logout', function(req, res, next) {
  req.session.destroy(()=>{
    res.send({
      message:'已注销',
      code:1,
      command:'redirect to login'
    });
  })

});

router.get('/', function(req, res, next) {
  res.send('admin router(like login and logout)');
});

module.exports = router;
